package simple05;

import java.util.concurrent.atomic.AtomicInteger;

//懒汉式
public class SessionCount2 {
    private AtomicInteger count = new AtomicInteger();
    private static SessionCount2 instance;

    private SessionCount2() {
    }

    //    方法存在多线程竞争 ，加同步代码块
    public synchronized static SessionCount2 getInstance() {
        if (instance == null) {
            instance = new SessionCount2();
        }
        return instance;
    }

    //    最优 双重加锁
    //  多次调用时,调用方法时不需要加锁 ,而是new 的时候才会竞争
    public static SessionCount2 getInstance2() {
        if (instance == null) {
            synchronized (SessionCount.class) {
                if (instance == null) {
                    instance = new SessionCount2();
                }
            }
        }
        return instance;
    }

    public int plus() {
        return count.incrementAndGet();
    }

    public int decrease() {
        return count.decrementAndGet();
    }

    public void showMessage() {
        System.out.println("当前人数" + this.count.get());
    }
}
